package cs2340.todolist.controller;

import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TimePicker;
import android.widget.ViewFlipper;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import cs2340.todolist.R;
import cs2340.todolist.application.ToDoListApplication;
import cs2340.todolist.model.Location;
import cs2340.todolist.model.account_management.AccountManager;
import cs2340.todolist.model.sqlite_database.ToDoItemDataSource;
import cs2340.todolist.view.MapPin;

/**
 * activity for adding items to the list
 * @author Robby
 *
 */
public class AddItemActivity extends MapActivity {
	
	//our accountManager
	private AccountManager accountManager;
	
	/**
	 * oncreate method called on activities first creation
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_information);
	
	}
	
	/**
	 * called whenever the activity is started up
	 */
	public void onStart() {
		super.onStart();

		//gets the accountmanager from the background application
        accountManager = ((ToDoListApplication)getApplication()).getSessionManager().getAccountManager();
        accountManager.changeContext(this);

        //creates variables for all the fields
        final EditText titleEditText = (EditText)findViewById(R.id.item_information_title);
        final Spinner typeSpinner = (Spinner)findViewById(R.id.item_information_type);	
        final DatePicker dueDatePicker = (DatePicker)findViewById(R.id.item_information_due_date);
        final TimePicker timePicker = (TimePicker)findViewById(R.id.item_information_time);
        final Spinner recurTypeSpinner = (Spinner)findViewById(R.id.item_information_recur_type);
        final EditText locationNameEditText = (EditText)findViewById(R.id.item_information_location);
        final EditText descriptionEditText = (EditText)findViewById(R.id.item_information_description);	
        final EditText addressEditText = (EditText)findViewById(R.id.item_information_enter_address);

        final Switch completionSwitch = (Switch)findViewById(R.id.item_information_completed);
        completionSwitch.setVisibility(View.GONE);
        
        
        final ViewFlipper viewFlipper = (ViewFlipper)findViewById(R.id.item_information_view_flipper);
        viewFlipper.setAnimation(AnimationUtils.loadAnimation(AddItemActivity.this, android.R.anim.fade_out));
        
        final Button showMapButton = (Button)findViewById(R.id.item_information_show_map);
        showMapButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
                viewFlipper.showNext();
        	}
        });
        
        final Button returnFromMapButton = (Button)findViewById(R.id.item_information_map_view_return);
        returnFromMapButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
                viewFlipper.showPrevious();
        	}
        });
        
        //creates a button and its listener for the finish creation button
        final Button createItemButton = (Button) findViewById(R.id.item_information_save_item_button);
        createItemButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//called when the create button is pressed
				if(titleEditText.getText().toString().equals("")) {
					System.out.println("invalid title");//change this to display it on screen
				}
				else {
					//create and open the data source
					ToDoItemDataSource dataSource = new ToDoItemDataSource(AddItemActivity.this);
					dataSource.open(); 
					//insert the item with the information from the fields
					dataSource.insertItem(	accountManager.getCurrentUser().getId(),  
											titleEditText.getText().toString(),
											new Location(locationNameEditText.getText().toString(), addressEditText.getText().toString()), 
											typeSpinner.getSelectedItemPosition(), 
											new Date(dueDatePicker.getYear(),dueDatePicker.getMonth(),dueDatePicker.getDayOfMonth(),timePicker.getCurrentHour(),timePicker.getCurrentMinute()), 
											recurTypeSpinner.getSelectedItemPosition(), 
											descriptionEditText.getText().toString(),
											false);
					
					dataSource.close();
					System.out.println("successful item creation"); //change this to display it on screen
					
					//open the home screen
					Intent homeScreenIntent = new Intent(AddItemActivity.this,HomeScreenActivity.class);
					startActivity(homeScreenIntent);
				}
			}
        });
        
        //creates a button adn listener for the cancel creation button
        final Button cancelItemButton = (Button) findViewById(R.id.item_information_cancel_button);
        cancelItemButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//called when the cancel button is pressed, just go back to the home screen
				Intent homeScreenIntent = new Intent(AddItemActivity.this,HomeScreenActivity.class);
				startActivity(homeScreenIntent);
			}
        });
        
        
    	final MapView map = (MapView)findViewById(R.id.item_information_map_view);
    	map.getOverlays().clear();
        map.invalidate();
        map.setBuiltInZoomControls(true);
        addressEditText.setOnKeyListener(new OnKeyListener() {
            
            Thread currentThread;
			@Override
			/**
			 * listen to key event and update the map simultaneously
			 * @param view
			 * @param keyCode
			 * @param event
			 */
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				
				if(currentThread == null || !currentThread.isAlive()) {
					map.getOverlays().clear();
			        map.invalidate();
					currentThread = new Thread() {
						 public void run() {
			                	try {
									Thread.sleep(800);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
			                	
			    				Location location = new Location(locationNameEditText.getText().toString(), addressEditText.getText().toString());
			    				GeoPoint geoPoint = location.geocode(AddItemActivity.this);
			    				MapPin mapPin = new MapPin(AddItemActivity.this);
			    				List<Overlay> mapOverlays = map.getOverlays();
			    				if(geoPoint != null) {
			    					mapPin.addOverlay(new OverlayItem(geoPoint, "", location.toString()));
			    					mapOverlays.add(mapPin);
			    					map.getController().animateTo(geoPoint);
			    					map.getController().setZoom(14);
			    				}
			    				
			    			}
					};
					currentThread.start();
					return false;
				}
				else return false;
			}
        	
        });
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
}
